/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串 ""。
 * <p>
 * 示例 1:
 * <p>
 * 输入: ["flower","flow","flight"]
 * 输出: "fl"
 * 示例 2:
 * <p>
 * 输入: ["dog","racecar","car"]
 * 输出: ""
 * 解释: 输入不存在公共前缀。
 */
class LongestCommonPrefix {

    public static void main(String[] args) {
        System.out.println(longestCommonPrefix(new String[]{"flower"}));
        System.out.println(longestCommonPrefix(new String[]{"flower", "flow", "flight"}));
        System.out.println(longestCommonPrefix(new String[]{"dog", "racecar", "car"}));
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        StringBuilder ex = new StringBuilder();
        for (int x = 0; ; x++) {
            if (x + 1 > strs[0].length()) {
                break;
            }
            char tmp = strs[0].charAt(x);
            int i = 1;
            for (; i < strs.length; i++) {
                if (x + 1 > strs[i].length()) {
                    break;
                }
                if (tmp != strs[i].charAt(x)) {
                    break;
                }
            }
            if (i == strs.length) {
                ex.append(tmp);
            } else {
                return ex.toString();
            }
        }
        return ex.toString();
    }

    /**
     * 移除了诸多变量
     * @param strs
     * @return
     */
    public static String longestCommonPrefix2(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        for (int x = 0; ; x++) {
            if (x + 1 > strs[0].length()) {
                break;
            }
            int i = 1;
            for (; i < strs.length; i++) {
                if (x + 1 > strs[i].length()) {
                    break;
                }
                if (strs[0].charAt(x) != strs[i].charAt(x)) {
                    break;
                }
            }
            if (i != strs.length) {
                return strs[0].substring(0, x);
            }
        }
        return strs[0];
    }
}